package cn.cs.mathgo.gateway.controller;

import cn.cs.mathgo.admin.modules.sys.feign.UserFeignClient;
import cn.cs.mathgo.common.AjaxJson;
import cn.cs.mathgo.common.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录地址
 */
@RestController
@RequestMapping("auth")
@Api("网关认证接口")
public class AuthController {
    @Autowired
    private UserFeignClient userFeignClient;
    @GetMapping("authentication/require")
    public ModelAndView require() {
        return new ModelAndView("ftl/login");
    }
    @GetMapping("/user")
    public Authentication user(Authentication authentication) {
        return authentication;
    }
    @Autowired
    private  RedisUtils redisUtils;
    @ApiOperation("登出接口")
    @GetMapping("logout")
    public Object logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        redisUtils.delete(request.getHeader("Authorization"));
        Map authorization = redisUtils.get(request.getHeader("Authorization"), Map.class);
        return AjaxJson.success();
    }

}
